-- INCLUDES
VFS.Include("LuaRules/Gadgets/Includes/utilities.lua")
VFS.Include("LuaRules/Gadgets/Includes/messagetypes.lua")

-- CONSTANTS
local GAIA_TEAM_ID = Spring.GetGaiaTeamID()
local LOCALPLAYER = Spring.GetMyPlayerID()
local LIMITWINDOWWIDTH = 100
local MAXUNITLIMIT = 20;

-- MEMBERS
local Chili
local Window
local limit
local windows = {}
local x
local y

-- SCRIPT FUNCTIONS
function doLimitUpdate(value)
	if DEBUG then Spring.Echo("changing limits to " .. value) end
	limit:SetCaption(value .. "/" .. MAXUNITLIMIT)
end

function addUnitLimitLabel()
	if DEBUG then Spring.Echo("adding limit label") end
	team = Spring.GetMyTeamID()
	r,g,b,a = Spring.GetTeamColor(team)
	limit = Chili.Label:New{
		x = 40,
		y = '10%',
		caption = "0/" .. MAXUNITLIMIT,
		fontsize = 13,
		autosize = false,
		textColor = {r,g,b,a},
		anchors = {left=true,bottom=true,right=true},
	}
	if DEBUG then Spring.Echo("limit label added") end	
end

-- WIDGET CODE
function widget:GetInfo()
	return {
		name		= "unit limit",
		desc		= "window to keep the unit limit",
		author		= "Sunspot",
		date		= "2011-06-14",
		license     = "GNU GPL v2",
		layer		= 2,
		enabled   	= true  --  loaded by default?
	}
end

function widget:Shutdown()
	for i=1,#windows do
		(windows[i]):Dispose()
	end
end

function widget:Initialize()
	
	if (not WG.Chili) then
		widgetHandler:RemoveWidget()
		return
	end

	Chili = WG.Chili
	Window = Chili.Window
	local screen0 = Chili.Screen0
	
	addUnitLimitLabel()	

	if DEBUG then Spring.Echo("creating window") end		
	window0 = Window:New{
		x = '50%',
		y = '15%',	
		dockable = true,
		parent = screen0,
		caption = "unit limit",
		draggable = true,
		resizable = false,
		dragUseGrip = true,
		clientWidth = 100,
		clientHeight = 20,
		backgroundColor = {0.8,0.8,0.8,0.9},
		skinName  = "DarkGlass",	
		
		children = {limit,}
	}
	windows[#windows+1] = window0
	if DEBUG then Spring.Echo("window created") end		
end

function widget:RecvLuaMsg(msg, playerID)
	if (playerID ~= LOCALPLAYER) then return end
	
	local tokens = split(msg,"-");
	if(tokens[1] == UNITLIMITUPDATE)then
		if DEBUG then Spring.Echo("unit limit update msg recieved : " .. msg) end		
		if DEBUG then Spring.Echo("fetching player info") end		
		local _,_,_,playerTeam = Spring.GetPlayerInfo(playerID)
		if DEBUG then Spring.Echo("player info fetched playerteam is " .. playerTeam) end		
		if(tostring(filterNil(tokens[2])) == tostring(playerTeam))then
			doLimitUpdate(filterNil(tokens[3]))
			if DEBUG then Spring.Echo("limit update done") end		
		end		
	end
end